$(function() {
      //所有列表图片预加载
      var question_type =  JSON.parse(localStorage.getItem('question_type'));
      if (question_type!=="pay_phone"&question_type!=="adviser1"&question_type!=="adviser2"&question_type!=="adviser3"&question_type!=="adviser4") {
        question_type = "pay_text"
      };
      citiesinit();
      function citiesinit(){
        $.get(apitest+'/lawyer/city?size=20', function(data){
            
        }, "json").error(function(data) {
          var status_code = $.parseJSON(data.responseText);
          layer.msg(status_code.message)
        }).success(function(data) {
           var obj = data.data;
           var str="";
           for(var i=0;i<20;i++){
              str+='<a href="javascript:void(0)"';
              str+='data-id="'+obj[i].city_code+'">'+obj[i].city_name+'</a>';
           }
           $("#citiesinit").append(str);
        });
      }
  // 地区的二级联动

    init();
    //初始化数据
    function init(){
      //数据调用
      province_Main(province_param,null);
      var city = $("#city").val();
    }

      //获取省份、城市的数据
    $("#province").change(function(){
      $("#city,#district").empty();
      var province_val =  $(this).val();
      city_Main(null,province_val);
      var params ='province_id='+province_val;
      if (province_val == "990000") {
        getListParams('',"");
      }else{
        getListParams('',params);
      }
      $("#city").show();
      $(".workscope a,.order a").removeClass('active');
      $(".issue a").eq(0).addClass("active")
      $(".order a").eq(0).addClass("active")
    })
    $("#city").change(function(){
      var province_val = $("#province").val();
      var city_val =  $(this).val();
      var params ='province_id='+province_val+'&city_id='+city_val;
      getListParams('',params);
    })

    //获取省份的数据
    function province_Main(province,_this){
      var province_url = jumpUrl+"/area/province";
      $.get(province_url, function(data){
            
          }, "json").error(function(data) {
            var status_code = $.parseJSON(data.responseText);
            layer.msg(status_code.message);
          }).success(function(data) {
              var obj = data.data;
              var options = '';
                $.each(obj, function(key, item) {
                    options+='<option value="'+item.key+'">'+item.value+'</option>';
                });
                $("#province").append(options);
                if(province){
                   $("#province option[value='"+province+"']").attr("selected",true);
                }
               
          });
    }
     //获取城市的数据
      function city_Main(city,_this){
        var city_url;
        if(!_this){
          city_url = jumpUrl+"/area/"+province_param+"/city";
        }else{
          city_url = jumpUrl+"/area/"+_this+"/city";
        }
       
      $.get(city_url, function(data){
        
        }, "json").error(function(data) {
          var status_code = $.parseJSON(data.responseText);
          layer.msg(status_code.message);
        }).success(function(data) {
            var obj = data.data;
            var options = '';
            $.each(obj, function(key, item) {
                options+='<option value="'+item.key+'">'+item.value+'</option>';
            });
            $("#city").append(options);
            if(city){
              $("#city option[value='"+city+"']").attr("selected",true);

            }
        });
    }
    //获取擅长领域的数据
    $.get(jumpUrl+'/lawyer/workscopes', function(data){
          
        }, "json").error(function(data) {
          var status_code = $.parseJSON(data.responseText);
          layer.msg(status_code.message);
        }).success(function(data) {
           var obj = data.data;
            var work_scope = obj;
            var src = '';
            $.each(work_scope, function(key, item) {
              src+='<a href="javascript:void(0);" data-id="'+item.key+'">'+item.value+'</a>';
            });
            $(".type-box").append(src);
    });
    
    // 获取到选中的值
    $("#field").change(function(){
        var params = null;
        var province_val = $("#province").val();
        var city_val =  $("#city").val();
        var field_val =  $(this).val();
        if(province_val !="" && city_val !="" ){
          params ='province_id='+province_val+'&city_id='+city_val+'&cat_id='+field_val;
        }else if(province_val !="" && city_val =="" ){
           params ='province_id='+province_val+'&cat_id='+field_val;
        }else{
          params ='cat_id='+field_val;
        }
        getListParams('',params);
        $(".trade a").eq(0).addClass("active").siblings().removeClass("active");
    })


  var q = getUrlParam('q');
  var search_init = $("#inquery_list_form");
  var searchurlq = search_init[0].action;
  var workscopes;
//滚动条拉到底部的时候去获取新的数据
  var stop=true;
  var pageNumb = 1;

  scrollUrl();

  $(document).on("click",".loadMore",function(e){
    if(stop==true){
        stop=false;
        scrollUrl();
        
    } 
    stopDefault(e);
  })


  //滚动调用的方法;
  function scrollUrl(){
    var location_searc = window.location.search;
    var scrollUrl = searchurlq+location_searc;
    var url;
    if(location_searc == ""){
      url = scrollUrl+'?page='+pageNumb++;
      getAllUrl(url)
      stop=true;
    }else{
      /*getParamt(0);*/
      url = scrollUrl+'&page='+pageNumb++;
      getAllUrl(url)
      stop=true;
    }
  }
  //根据搜索条件查询
  $(document).on("click","#subSearch",function(e){

    var keyword = $("#keyword").val();
    var q = getUrlParam("q");
    if(keyword != undefined && q == undefined ||  keyword == q){
      getParamt(0);
    }else if(q != keyword){
      getParamt(1);
    }else if(q != undefined && keyword == undefined){
      var params ='q='+keyword;
      getListParams('',params);
    }else{
      getListParams('int','');
    }
    stopDefault(e);
  })
  $(".search-input").focus(function(e){  // 获得焦点
        $(".search-input").css({"border":"1px solid #48b4ff"});
        $(".search-icon").css("background","url("+jumpUrl+"/img/question2/searchs.png)");
      }).blur(function(){     // 失去焦点
        $(".search-input").css({"border":"1px solid #e8e8e8"});
        $(".search-icon").css("background","url("+jumpUrl+"/img/question2/search.png)");
  });

          //搜索
  $('.search-input').bind('input propertychange', function(e) {  
      runTiming(); 
  });
  function search_q(){
    var keyword = $(".search-input").val();
    var q = getUrlParam("q");
    if(keyword != undefined && q == undefined ||  keyword == q){
      getParamt(0);
    }else if(q != keyword){
      getParamt(1);
    }else if(q != undefined && keyword == undefined){
      var params ='q='+keyword;
      getListParams('',params);
    }else{
      getListParams('int','');
    }
  }
  //执行搜索的全局方法
  var timePromise;
  var runTiming = function(){
    if(timePromise){
        clearTimeout(timePromise);
        timePromise = undefined;
    }
    timePromise = setTimeout(function(){
        search_q();
        
    }, 2000);
    return timePromise;
  }

  //根据条件查询
  $(document).on("click","ul.area-wrap li a ",function(e){
    var qthis = $(this);
    getClickVal(qthis);
    getParamt(2);
    stopDefault(e);
  });

  //获取参数，处理被收藏书签的情况
  function getParamt(index){
      var locat_area = getUrlParam("city_id"); 
      var locat_issue = getUrlParam("experience"); 
      var locat_trade = getUrlParam("cat_id"); 
      var locat_order = getUrlParam("order_by");
      var locat_q = getUrlParam("q");
      var keyword = $("#keyword").val();
      var params = [];
      if (locat_area) {
        params.push('city_id=' + locat_area);
      }
      if (locat_issue) {
        params.push('experience=' + locat_issue);
      }
      if (locat_trade) {
        params.push('cat_id=' + locat_trade);
      }
      if (locat_order) {
        params.push('order_by=' + locat_order);
      }

      if(index == 0){ //index=0初始化
        if(locat_q == null && keyword != ""){
           params.push('q=' + keyword);
        }else if(locat_q == null && keyword == ""){
          return false;
        }else if(locat_q != null && locat_q != "" && keyword == ""){
          params.push('q=' + locat_q);
          $("#keyword").val(locat_q);
        }else{
          return false;
        }

      }

     if(index == 1){ //输入搜索条件查找
        if (locat_q) {
          if(locat_q != keyword){
            params.push('q=' + keyword);
          }else{
            params.push('q=' + locat_q);
          }
        }else{
          params.push('q=' + keyword);
        }
      }

    if(index == 2){ //点击a标签根据条件查找
        var area = $(".area a.active").attr("data-id");
        var issue = $(".issue a.active").attr("data-id");
        var trade = $(".trade a.active").attr("data-id");
        var order = $(".order a.active").attr("data-id");
        var keyword = $("#keyword").val();
        var value_q = getUrlParam("q");
        var params = [];
        if (question_type) {
          params.push('type=' + question_type);
        }
        if (area) {
          params.push('city_id=' + area);
        }
        if (issue) {
          params.push('experience=' + issue);
        }
        if (trade) {
          params.push('cat_id=' + trade);
        }
        if (order) {
          params.push('order_by=' + order);
        }
        

        if(value_q != null && value_q != undefined){
          if(value_q != keyword){
            params.push('q=' + keyword);
          }else{
            params.push('q=' + value_q);
            $("keyword").val(value_q);
          }
        }else{
          var q = $("keyword").val();
          if(q != null && q != undefined){
             params.push('q=' + q);
          }
          
        }

      }
      //console.info(params)
      params = params.join('&');
      getListParams('',params);

  }

  //点击选中添加背景颜色
  function getClickVal(qthis){
      var $this = qthis;
      var parenta = $this.parent();
      var worksa = parenta.find(".workscope").children("a");
      var any = parenta.parent().children("a");
      //不同级
      any.removeClass("active");
      worksa.removeClass("active");
      //同级情况下
      $this.addClass("active").siblings().removeClass("active");
      //获取到选中的值
      var thisVal = $this.attr("data-id");
  }
  //获取数据调用的显示的列表
  function getListParams(init,params){
     //共用获取数据的请求路径
     var search = $("#inquery_list_form");
     var searchurlq = search[0].action;
     var url;
      if(init != ""){
        url = searchurlq;//初始化
        //url = searchurlq+'?rows_per_page=1000';
        $("#page").empty(); //删除tbody中已经存在的数据
        getAllUrl(url);
      }
      if(params != ""){
        url = searchurlq+'?'+params; //带参数
        var thisUrl = location.href.split("?")[0]+'?'+params;
        window.history.pushState('obj', document.title, thisUrl);
        $("#page").empty(); //删除tbody中已经存在的数据
        getAllUrl(url);
      }else{
        url = searchurlq; //带参数
        var thisUrl = location.href.split("?")[0];
        window.history.pushState('obj', document.title, thisUrl);
        $("#page").empty(); //删除tbody中已经存在的数据
        getAllUrl(url);
      }
  }

      //获取url
      function getAllUrl(url){
          var loading = '<dl class="slInfo" style="border:none;margin:10px 0 0 0;height:40px;"><div class="loading">加载中...</div></dl>'; 
          $("#page").append(loading);
          var str  =  "";
          // console.info(url);
          $.get(url, function(data){
          }, "json").error(function(data) {
            var status_code = $.parseJSON(data.responseText);
            layer.msg(status_code.message)

          }).success(function(data) {
            $(".loading").parent().remove();
            	var companyStore = JSON.parse(localStorage.getItem("companyStore"));//localStorage获取出来
              var obj = data.data;
              console.info(obj)
              if(obj.length > 0){
                console.log(obj.length)
                for(var i=0; i<obj.length; i++)  
                {
                  if (obj.length < 10) {
                    $(".loadMore").css({
                      "display" : "none"
                    })
                  } else {
                    $(".loadMore").css({
                      "display" : ""
                    })
                  }
                  var work_scope = obj[i].work_scope;
                  var obj_workscopes = '';
                  $.each(work_scope, function(key, item) {
                      obj_workscopes+='<label value="'+item.key+'">'+item.value+'</label> &nbsp;';
                  });
                  if (obj[i].address== null || obj[i].address == "") {obj[i].address = ""};
                  var practice_period = (obj[i].practice_period == null || obj[i].practice_period == "") ? obj[i].practice_period = "": obj[i].practice_period;
                   //返回数据位json格式，遍历json，拼凑成table中的行
                  
                  str +='<li>'
                    str +='<div class="fl"><a target="_blank" href="'+jumpUrl+'/lawyer/'+obj[i].id+'?'+timestamps+'"><img src="'+obj[i].avatar+'" width="80" height="80" style="border-radius: 50%;"></a></div>'
                    str +='<div class="fl font16 lv-info-box">'
                     str +=' <p class="font20 lv-name"><a target="_blank" href="'+jumpUrl+'/lawyer/'+obj[i].id+'?'+timestamps+'" class="lvrealname">'+obj[i].realname+'</a></p>'
                      str +='<p class="colorF address">'+ obj[i].province +'-'+obj[i].city+'</p>'
                      str +='<p class="colorF">'
                        if (obj[i].company_name== null || obj[i].company_name == "") {
                          str +=''
                        }else{
                          str += obj[i].company_name +'&nbsp;&nbsp;&nbsp;&nbsp;'
                        }
                        if (obj[i].practice_period== null || obj[i].practice_period == "") {
                              str +='&nbsp;'
                          }else{
                            str += obj[i].practice_period+'经验 </p>'
                        }
                      str +='</p>'
                     str +=' <p class="law-type">'
                     if (obj[i].work_scope.length >= 3) {
                        obj[i].work_scope.length = 3;
                      }
                      for (var beGood = 0; beGood < obj[i].work_scope.length; beGood++) {
                        str +='<span>'+obj[i].work_scope[beGood].value+'</span>'
                      }
                     str +='</p>'
                    
                    str +='</div>'
                    str +='<div class="fl textac font14">'
                      str +='<p class="colorC">'+obj[i].case_count+'</p>'
                      str +='<p class="colorD">接单数</p>'
                      str +='<p class="colorC"  style="margin-top:20px;">'+obj[i].average_evaluate_score+'</p>'
                      str +='<p class="colorD">评分</p>'
                    str +='</div>'
                    str +='<div class="fr">'
                      str +='<div class="colorD" style="text-align:right;">'
                        if (question_type=="pay_phone") {
                          str +='<span class="colorC">'+obj[i].phone_reply_fee+'</span>'
                        }else if (question_type=="adviser1"){
                          str +='<span class="colorC">'+companyStore[0].price+'</span>'
                        }else if (question_type=="adviser2"){
                          str +='<span class="colorC">'+companyStore[1].price+'</span>'
                        }else if (question_type=="adviser3"){
                          str +='<span class="colorC">'+companyStore[2].price+'</span>'
                        }else if (question_type=="adviser4"){
                          str +='<span class="colorC">'+companyStore[3].price+'</span>'
                        }else{
                          str +='<span class="colorC">'+obj[i].text_reply_fee+'</span>'
                        }
                      str +='<span class="font14"> 元/次</span></div>'
                      if (islogin) {
                        if (is_lawyer) {
                          str +='<a><div class="question_but" style="margin-top:65px;">选Ta为我服务</div></a>'
                        }else{
                          str +='<a href="'+jumpUrl+'/question/fill_in_view/'+obj[i].id+'"><div class="question_but" style="margin-top:65px;" data-id="'+obj[i].phone_reply_fee+'">选Ta为我服务</div></a>'
                        }
                      }else{
                        str +='<a><div class="question_but" style="margin-top:65px;">选Ta为我服务</div></a>'
                      }
                    str +='</div>'
                  str +='</li>'
                  
                }
            }else{
              str+='<li class="textac"><span class="noData2"></span></li>'
            }
            //追加如tbody中 
            $("#page").append(str); 
            $('#question_but').attr("disabled",true);
        });
    

    }

  $(document).on('click', '.question_but', function(e) {
    if(islogin == "" || islogin == null){
      $(".loginPopup").click();
    }else if (is_lawyer == "1") {
      layer.msg("律师不能咨询！");
    }
  });

  //点击关注
  $(document).on('click', '.attention', function(e) {
    if(islogin == "" || islogin == null){
      layer.msg("请登录后在关注！");
      return false;
    }else{
      var $this = $(this);
      var follow_id = $(this).attr("data-id");
      var params = {};
      params['follow_id'] = follow_id;
      params['user_id'] = user_id;
      var url = jumpUrl+'/follow';
      $.post(url,params,function(data){
        
        }, "json").error(function(data) {
          var error =  $.parseJSON(data.responseText);
          $.each(error.error_messages, function(i, item){
            layer.msg(item[0]);
          });

        }).success(function(data) {
          var obj = data.data;
          layer.msg(obj);
          $this.text("取消关注");
          $this.attr("class","unfollow");
        })
      }
      stopDefault(e);
    });
    //取消关注
  $(document).on('click', '.unfollow', function(e) {
    if(islogin == "" || islogin == null){
      layer.msg("请登录后在关注！");
      return false;
    }else{
      var $this = $(this);
      var follow_id = $(this).attr("data-id");
      var token = $("input:[name='_token']").val();
      var params = {};
      params['follow_id'] = follow_id;
      params['user_id'] = user_id;
      params['_token'] = token;
      var url = jumpUrl+'/follow/remove';
      $.post(url,params,function(data){
        
        }, "json").error(function(data) {
          var error =  $.parseJSON(data.responseText);
          $.each(error.error_messages, function(i, item){
            layer.msg(item[0]);
          });

        }).success(function(data) {
          var obj = data.data;
          layer.msg(obj);
          $this.text("关注");
          $this.attr("class","attention");
        })
      }
      stopDefault(e);
    });
    



  
    //获取页面返回的参数，并且把有值的变为选中状态
    var area = $(".area .workscope a"); 
    if(area.length > 0){  //判断是否有数据
      select_val();
    }else{
      setTimeout(function() {        
       select_val();
      }, 3000);    
    }
    function select_val(){
        var value_area = getUrlParam("city_id");
        var value_issue = getUrlParam("experience");
        var value_trade = getUrlParam("cat_id");
        var value_order = getUrlParam("order_by");
        var value_q = getUrlParam("q");

        var area = $(".area .workscope a");
        var issue = $(".issue a");
        var trade = $(".trade a");
        var order = $(".order a");  

        if( value_area != null){
          for(var i=0;i<area.length;i++){
            var val_area = area[i].attributes[1].value;
            if(val_area == value_area){
              area[i].className = "active";
              break;
            }
          }
        }else{
          //$(".area a").eq(0).addClass("active")
        }
        if( value_issue != null){
          for(var i=0;i<issue.length;i++){
            var val_issue = issue[i].attributes[1].value;
            if(val_issue == value_issue){
              issue[i].className = "active";
              break;
            }
          }
        }else{
          $(".issue a").eq(0).addClass("active")
        }

        if( value_trade != null){
          for(var i=0;i<trade.length;i++){
            var val_trade = trade[i].attributes[1].value;
            if(val_trade == value_trade){
              trade[i].className = "active";
              break;
            }
          }
        }else{
          //$(".trade a").eq(0).addClass("active")
        }

        if( value_order != null){
          for(var i=0;i<order.length;i++){
            var val_order = order[i].attributes[1].value;
            if(val_order == value_order){
              order[i].className = "active";
              break;
            }
          }
        }else{
         // $(".order a").eq(0).addClass("active")
        }
        if( value_q != null){
          $("#keyword").val(value_q);
        }else{
          $("#keyword").val("");
        }
        
    }
//获取擅长领域的数据
    $.get(user_lawyer_url, function(data){
        }, "json").error(function(data) {
          var status_code = $.parseJSON(data.responseText);
          layer.msg(status_code.message);
        }).success(function(data) {
           var obj = data.data;
            var work_scope = obj;
            var options = '';
            $.each(work_scope, function(key, item) {
                options+='<option value="'+item.key+'">'+item.value+'</option>';
            });
            $("#work_scope").append(options);
        });
//提交咨询
      $(".quesissSbmint .subAdvisory").click( function (e) {
          var title = $.trim($("#title").val());
          var content = $.trim($("#content").val());
          var work_scope = $.trim($("#work_scope").val());
          var type = $(".caseType input:checked").attr('value');
          var WeiXinImg = '<div class="weixincode"><br><br>'
                  WeiXinImg+='<p>提交成功！感谢您的咨询，律团网的律师会尽快为您解答！</p><br>'
                  WeiXinImg+='<p class="WeiXinImg"></p>'
                  WeiXinImg+='<br><p>扫一扫<span style="color:#ff446f">关注服务号，随时随地收到回复</span></p>'
                WeiXinImg+='</div>'
          if(work_scope.length < 1){
              layer.msg('请选择案件类型！', {time: 2000});
              return false;
          }else if(title.length<1){
              layer.msg('标题不能为空！', {time: 2000});
              return false;
          }else if(title.length>15){
              layer.msg('标题不能超过15字！', {time: 2000});
              return false;
          }else if(content.length < 1){
              layer.msg('内容不能为空！', {time: 2000});
              return false;
          }else if(content.length < 20){
              layer.msg('内容字数不能小于20字！', {time: 2000});
              return false;
          }else{var loading = layer.msg('加载中...', {icon: 16});

          var inquery = $("#inquery_create_form");
          var url = jumpUrl+'/center/question/create/'+type;
          $.post(url, inquery.serialize(),
             function(data){
                $(':input',inquery).not(':button, :submit, :reset, :hidden').val(''); 
                if(islogin == "" || islogin == null){
                    layer.msg("请先登录");
                }else{
                    $(this).attr("disabled", true);
                    layer.closeAll();
                    // layer.msg("提交成功！感谢您的咨询，律团网的律师会尽快为您解答！");
                    var weixincode = layer.open({
                          type: 1, //基本层类型  可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）。 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
                          title: false, //标题
                          closeBtn: true,  //关闭按钮
                          shade:0.3,  //遮罩默认是0.3透明度
                          shadeClose: false,  //是否点击遮罩关闭
                          area: ['450px', '360px'],
                          skin: 'yourclass', //样式类名
                          content: WeiXinImg //内容
                    });
                }
                layer.close(loading);
             }, "json").error(function(data) {
               var obj = $.parseJSON(data.responseText);
               layer.msg(obj);
             }).success(function(data){

              var obj = data.data;
              var id = obj.id;
              // window.location.href=jumpUrl+'/center/pay/question/'+id+'/to_pay';
             });
             
             return true;
      }
      stopDefault(e);
  });

  //上传图片的插件
      //初始化jQuery的文件上传控件
      $('#avatar_file').fileupload({
          limitMultiFileUploads : 1,
          limitMultiFileUploadSize : 1,
          limitMultiFileUploadSizeOverhead : 512,
          limitConcurrentUploads : 1,
            sequentialUploads : true,
          headers: 
            {"Accept":"application/json"}, //必须有
              dataType: "json", //表示返回值类型，不必须
          formData:{
            _token:token
          },
          messages: {uploadedBytes: 'Uploaded bytes exceed file size'},
          done: function (e, data) {//设置文件上传完毕事件的回调函数 
              var obj = data.result;
              var avatar = obj.data.file_path;
              var file_name = obj.data.file_name;
              var fileExt=( /[^.]+$/.exec(avatar.toUpperCase())); 
              var type = fileExt[0];
              $(".btn-success").append('<input type="hidden" name="file_paths[]" value="'+avatar+'"><input type="hidden" name="file_names[]" value="'+file_name+'">');
              layer.msg("上传文件成功！");
                $(".filename ul").append('<li>'+file_name+'&nbsp;&nbsp;<a class="delet" href="javascript:void(0);" style="color:#004799;" title="删除">删除</a></li>');//文件名
                $(".avatar_js_cover").show();
                 var fileLen = $(".filename ul li").length;
                 var nameLen = $("input:hidden[name='file_names[]']").length;
                 if(fileLen>=2){
                     $('#avatar_file').attr("disabled",true);
                 }
              
              
            },
            fail: function(e, data) {
                //错误提示
                /*console.info(data)*/
            }
        });

    /* 公用js */
  $(".btn-more").toggle(
      function () {
        $(this).parent().find(".workscope").addClass("unfolded")
      },
      function () {
        $(this).parent().find(".workscope").removeClass("unfolded");
      }
  );

  
  //删除上传的文件
  $(document).on( "click", ".delet", function(e) {
     $this = $(this).parent();
     $this.hide();
     index = $this.index();
     $(this).parent().remove();
     $("input:hidden[name='file_paths[]']").eq(index).remove();
     $("input:hidden[name='file_names[]']").eq(index).remove();
     var fileLen = $(".filename ul li").length;
     var nameLen = $("input:hidden[name='file_names[]']").length;
     if(fileLen<2){
       $('#avatar_file').attr("disabled",false);
     }
    stopDefault(e);
  })



}); 

